package com.credithc.signature.manager.service;

import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.signature.common.mapper.ProductSignHistoryMapper;
import com.credithc.signature.common.mapper.ProductSignMapper;
import com.credithc.signature.common.po.ProductSign;
import com.credithc.signature.common.po.ProductSignHistory;
import com.credithc.signature.manager.client.AuthClient;
import com.credithc.signature.manager.ro.ChannelRo;
import com.credithc.signature.manager.ro.ProductSignRo;
import com.credithc.signature.manager.ro.TokenRo;
import com.credithc.signature.manager.vo.ChannelVo;
import com.credithc.signature.manager.vo.ProductSignHistoryVo;
import com.credithc.signature.manager.vo.ProductSignVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhanghanqiu181212@credithc.com
 * @Date 2019/10/29 17:40
 */
@Service
public class ProductSignService {

    @Autowired
    private ChannelMService channelMService;

    @Autowired
    private ProductSignMapper productSignMapper;

    @Autowired
    private ProductSignHistoryMapper productSignHistoryMapper;

    @Autowired
    private AuthClient authClient;

    public PageInfo<ChannelVo> queryAll(ChannelRo channelRo) {
        PageInfo<ChannelVo> channelVoPageInfo = channelMService.queryAll(channelRo);
        List<ChannelVo> list = channelVoPageInfo.getList();
        List<String> productCodes = new ArrayList<>();
        Map<String, ChannelVo> map = new HashMap<>();
        if (list == null || list.isEmpty()) {
            return channelVoPageInfo;
        }
        for (ChannelVo cv : list) {
            map.put(cv.getChannelNo(), cv);
            productCodes.add(cv.getChannelNo());
            cv.setProductSignStr("  中金  <font color='red'>100%</font>  懒猫  <font color='red'>0%</font>");
        }
        Example example = new Example(ProductSign.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("productCode", productCodes);
        List<ProductSign> productSigns = productSignMapper.selectByExample(example);
        for (ProductSign p : productSigns) {
            ChannelVo channelVo = map.get(p.getProductCode());
            channelVo.setCreateTime(p.getEffectiveTime());
            if ("  中金  <font color='red'>100%</font>  懒猫  <font color='red'>0%</font>".equals(channelVo.getProductSignStr())) {
                channelVo.setProductSignStr("");
            }
            channelVo.setProductSignStr(channelVo.getProductSignStr() + "  " + p.getThirdPartyName() + "  <font color='red'>" + p.getPercentage() + "%</font>");
        }


        return channelVoPageInfo;
    }

    public ProductSignVo getInfoByProductCode(String productCode) {
        ProductSignVo productSignVo = new ProductSignVo();
        List<ProductSignHistoryVo> productSignHistoryVos = new ArrayList<>();
        productSignVo.setProductSignHistoryVoList(productSignHistoryVos);
        ChannelRo channelRo = new ChannelRo();
        channelRo.setCode(productCode);
        channelRo.setPageNo(1);
        channelRo.setPageSize(1);
        PageInfo<ChannelVo> channelVoPageInfo = channelMService.queryAll(channelRo);
        List<ChannelVo> list = channelVoPageInfo.getList();
        if (list != null && !list.isEmpty()) {
            productSignVo.setChannelVo(list.get(0));
            Example example = new Example(ProductSignHistory.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("productCode", productCode);
            List<ProductSignHistory> productSignHistories = productSignHistoryMapper.selectByExample(example);
            Map<Date, ProductSignHistoryVo> map = new HashMap<>();
            for (ProductSignHistory psh : productSignHistories) {
                ProductSignHistoryVo productSignHistoryVo = map.get(psh.getEffectiveTime());
                Integer percentage = psh.getPercentage();
                if (percentage == null) {
                    percentage = 0;
                }
                if (productSignHistoryVo == null) {
                    productSignHistoryVo = new ProductSignHistoryVo();
                    productSignHistoryVos.add(productSignHistoryVo);
                    map.put(psh.getEffectiveTime(), productSignHistoryVo);
                    productSignHistoryVo.setEffectiveTime(psh.getEffectiveTime());
                    productSignHistoryVo.setRemark(psh.getRemark());
                    productSignHistoryVo.setProductSignStr("  " + psh.getThirdPartyName() + "  <font color='red'>" + percentage + "%</font>");
                    ChannelVo channelVo = productSignVo.getChannelVo();
                    productSignHistoryVo.setChannelName(channelVo.getChannelName());
                    productSignHistoryVo.setChannelNo(channelVo.getChannelNo());
                    productSignHistoryVo.setProductCode(channelVo.getProductCode());
                    productSignHistoryVo.setTenant(channelVo.getTenant());
                } else {
                    productSignHistoryVo.setProductSignStr(productSignHistoryVo.getProductSignStr() + "  " + psh.getThirdPartyName() + "  <font color='red'>" + percentage + "%</font>");
                }
            }
        } else {
            return null;
        }
        return productSignVo;
    }

    public String save(ProductSignRo productSignRo, String token) {
        Example example = new Example(ProductSign.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productCode", productSignRo.getProductCode());
        List<ProductSign> productSigns = productSignMapper.selectByExample(example);
        //获取当前登录人
        String userId = null;
        String userName = null;
        try {
            Message<TokenRo> userInfoByToken = authClient.getUserInfoByToken(token);
            TokenRo data = userInfoByToken.getData();
            userId = data.getEhrId();
            userName = data.getUserName();
        } catch (Exception e) {
            return "请重新登陆";
        }
        // 插入初始信息
        if (productSigns == null || productSigns.size() == 0) {
            String remark = productSignRo.getRemark();
            String productCode = productSignRo.getProductCode();
            List<ProductSignRo.ProductRo> productRoList = productSignRo.getProductRoList();
            for (ProductSignRo.ProductRo productRo : productRoList) {
                ProductSign product = buildProductPo(userId, userName, new Date(), remark, productCode, productRo);
                productSignMapper.insert(product);
            }
        } else {
            // 1.将当前信息记录到历史表
            for (ProductSign ps : productSigns) {
                Long id = ps.getId();
                ps.setId(null);
                productSignHistoryMapper.insert(ps);
                productSignMapper.deleteByPrimaryKey(id);
            }
            // 2.将最新的信息进行记录
            String remark = productSignRo.getRemark();
            String productCode = productSignRo.getProductCode();
            List<ProductSignRo.ProductRo> productRoList = productSignRo.getProductRoList();
            for (ProductSignRo.ProductRo productRo : productRoList) {
                ProductSign product = buildProductPo(userId, userName, new Date(), remark, productCode, productRo);
                productSignMapper.insert(product);
            }
        }
        return null;
    }

    /**
     * 封装ProductPo
     *
     * @param userId
     * @param userName
     * @param date
     * @param remark
     * @param productCode
     * @param productRo
     * @return
     */
    private ProductSign buildProductPo(String userId, String userName, Date date, String remark, String productCode, ProductSignRo.ProductRo productRo) {
        String productSign = productRo.getProductSign();
        Integer percentage = productRo.getPercentage();
        String productName = productRo.getProductName();
        ProductSign product = new ProductSign();
        product.setProductCode(productCode);
        product.setPercentage(percentage);
        product.setMethodName(productSign);
        product.setThirdPartyName(productName);
        product.setEffectiveTime(date);
        product.setOperatorId(userId);
        product.setOperatorName(userName);
        product.setRemark(remark);
        return product;
    }
}
